<template>
  <addEditQusetionnaireView ref="addEditQusetionnaireView" />
  <addFileView ref="addFileView" />

  <el-dialog v-model="dialogTableVisible" title="请选择设计问卷模式">
    <div class="box">
      <div @click="changeMode(1)" :class="changeModeIndex == 1 ? 'checkedMode' : 'unCheckedMode'">
        <p class="p1">保留答卷</p>
        <p class="p2">保留所有答卷</p>
      </div>

      <div @click="changeMode(2)" :class="changeModeIndex == 2 ? 'checkedMode' : 'unCheckedMode'">
        <p class="p1">删除答卷</p>
        <p class="p2">清空所有答卷</p>
      </div>

      <div @click="changeMode(3)" :class="changeModeIndex == 3 ? 'checkedMode' : 'unCheckedMode'">
        <p class="p1">复制此问卷并去编辑</p>
        <p class="p2">创建新问卷</p>
      </div>
    </div>

    <div class="box-btn">
      <el-button type="primary" @click="nextOperate()">下一步</el-button>
    </div>
  </el-dialog>

  <el-main>
    <div class="teacher">
      <div class="app-table">
        <div class="app-body">
          <div class="app-search">
            <el-form :inline="true" class="demo-form-inline" v-model="form">
              <el-form-item label="标题">
                <el-input placeholder="请输入标题" v-model="form.title"></el-input>
              </el-form-item>
              <el-form-item label="问卷状态">
                <el-select placeholder="请选择问卷状态" clearable v-model="form.status" style="width:190px;">
                  <el-option label="未启用" :value="0"> </el-option>
                  <el-option label="已发布" :value="1"> </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="创建人">
                <el-input
                  placeholder="请输入创建人"
                  v-model="form.createName"
                ></el-input>
              </el-form-item> -->
              <el-form-item>
                <el-button type="primary" @click="onSubmit" plain>搜索</el-button>
                <el-button type="success" @click="add" plain>创建问卷</el-button>
                <!-- <el-button type="warning" @click="exportExcel" plain
                  >导出报表</el-button
                >
                <el-button type="danger" @click="importExcel" plain
                  >批量导入<el-icon class="el-icon--right"><Upload /></el-icon
                ></el-button> -->
              </el-form-item>
            </el-form>
          </div>
          <el-table :data="list" style="width: 100%" border :row-class-name="tableRowClassName">
            <el-table-column prop="id" label="主键" width="80" />
            <el-table-column prop="title" label="标题" />
            <!-- <el-table-column prop="content" label="描述" /> -->
            <el-table-column prop="status" label="问卷状态" width="150">
              <template #default="scope">
                {{ scope.row.status == 1 ? '已发布' : '未启用' }}
                <!-- <el-switch
                  v-model="scope.row.status"
                  size="large"
                  active-text="发布"
                  inactive-text="停用"
                  disabled
                  @click.native="beforeChange(scope.$index, scope.row.status)"
                  :active-value="1"
                  :inactive-value="0"
                /> -->
              </template>
            </el-table-column>
            <!-- <el-table-column prop="count" label="收到数据" width="100" /> -->
            <!-- <el-table-column prop="type" label="类型" /> -->
            <!-- <el-table-column prop="createName" label="创建人" /> -->
            <el-table-column prop="createTime" label="创建时间" :formatter="formatDate" width="170" />
            <!-- <el-table-column prop="startTime" label="开始日期" /> -->
            <!-- <el-table-column prop="endTime" label="结束时间" /> -->
            <!-- <el-table-column prop="updateTime" label="更新时间" /> -->
            <el-table-column label="操作" width="320px">
              <template style="display: block" #default="scope">
                <el-button size="small" type="warning" @click="goAnalysis(scope.row.uuid)">分析
                </el-button>
                <el-button size="small" type="primary" @click="designTip(scope.row)">设计
                </el-button>
                <el-button type="info" size="small" @click="copyQusetionnaire(scope.row.id)">复制
                </el-button>
                <el-button size="small" type="success" @click="editQusetionnaire(scope.row)">设置
                </el-button>

                <el-button size="small" type="danger" @click="deleteQusetionnaire(scope.row.id)">删除
                </el-button>

              </template>
            </el-table-column>
            <template v-slot:empty>
              <el-empty description="暂无数据"></el-empty>
            </template>
          </el-table>
          <el-config-provider :locale="locale">
            <el-pagination :total="total" :page-size="limit" :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper" @size-change="changePageSize"
              @current-change="changeCurrentPage">
            </el-pagination>
          </el-config-provider>
        </div>
        <bottomView />
      </div>
    </div>
  </el-main>
</template>
<script>
import addEditQusetionnaireView from "@/components/questionnaire/addEditQusetionnaire.vue";
import addFileView from "@/components/addExcelFile.vue";
import { ElConfigProvider, ElMessageBox, ElMessage } from "element-plus";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { httpService } from "@/utils/httpService";
import bottomView from "@/components/bottom.vue";

import {
  Picture as IconPicture,
  Upload,
  ArrowDownBold,
} from "@element-plus/icons-vue";

export default {
  name: "QusetionnaireListView",
  data() {
    return {
      type: 0,
      title: "",
      page: 0,
      pageSize: 10,
      total: 0,
      limit: 10,
      list: [],
      changeModeIndex: 0,
      newTitle: "",
      nowUuid: "",
      nowId: 0,
      dialogTableVisible: false,
      form: {
        title: "",
        content: "",
        createName: "",
        status: "",
      },
    };
  },
  components: {
    addEditQusetionnaireView,
    addFileView,
    IconPicture,
    ElConfigProvider,
    ElMessageBox,
    ElMessage,
    Upload, bottomView,
    ArrowDownBold,
  },
  setup() {
    return {
      locale: zhCn,
    };
  },
  mounted() {
    this.getQusetionnaireList();
  },
  watch: {
    $route() {
      this.getQusetionnaireList();
    },
  },
  methods: {
    nextOperate() {
      if (this.changeModeIndex == 1) {
        this.goDesign(this.nowUuid);
        this.dialogTableVisible = false;
      } else if (this.changeModeIndex == 2) {
        //删除问卷答案
        httpService(
          "/javaApi/qtAnswer/deleteByQuestionnaireId",
          "id=" + this.nowId,
          "post"
        ).then((data) => {
          if (data.code == 200) {
            this.goDesign(this.nowUuid);
            this.dialogTableVisible = false;
          } else {
            ElMessage.error("操作失败，请重试！");
          }
        });
      }
      if (this.changeModeIndex == 3) {
        //复制问卷答案
        this.copyQusetionnaire(this.nowId);
        this.dialogTableVisible = false;
      }
    },
    changeMode(index) {
      this.changeModeIndex = index;
    },
    beforeChange(index, status) {
      let title = "";
      if (status == 0) {
        title = "发布";
      } else {
        title = "停用";
      }

      let isChange = false;
      ElMessageBox.confirm("确定要" + title + "此问卷吗？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          isChange = true;
          if (status == 0) {
            this.list[index].status = 1;
          } else {
            this.list[index].status = 0;
          }
        })
        .catch((value) => { });

      return new Promise((resolve) => {
        setTimeout(() => {
          return resolve(isChange);
        }, 1000);
      });
    },
    switchStatus(e) {
      console.log("===========");
    },
    add() {
      this.$refs.addEditQusetionnaireView.title = "创建问卷";
      this.$refs.addEditQusetionnaireView.personnelType = this.type;
      this.$refs.addEditQusetionnaireView.dialogFormVisible = true;
      this.$refs.addEditQusetionnaireView.isTemplate = 0;
    },
    editQusetionnaire(obj) {
      this.$refs.addEditQusetionnaireView.title = "问卷设置";
      this.$refs.addEditQusetionnaireView.getQusetionnaireById(obj.id);
      this.$refs.addEditQusetionnaireView.dialogFormVisible = true;
      this.$refs.addEditQusetionnaireView.isTemplate = 0;
    },
    copyQusetionnaire(id) {
      ElMessageBox.prompt("请输入新标题，未输入则使用原标题", "问卷复制", {
        confirmButtonText: "复制为新问卷",
        cancelButtonText: "复制为问卷模版",
        closeOnClickModal: false,
        closeOnPressEscape: false,
        closeOnHashChange: false,
        showClose: false,
        type: "warning",
        beforeClose: (action, instance, done) => {
          this.newTitle = "";
          if (action === "cancel" && instance.inputValue != null) {
            this.newTitle = instance.inputValue;
          }
          done();
        },
      })

        .then((value) => {
          let title = "";
          if (value.value != null) {
            title = value.value;
          }
          httpService(
            "/javaApi/qtQuestionnaire/copyQuestionnaire",
            "id=" + id + "&flag=1&title=" + title,
            "post"
          ).then((data) => {
            if (data.code == 200) {
              ElMessage.success("复制成功");
              this.goDesign(data.obj);
              this.getQusetionnaireList();
            } else {
              ElMessage.error("复制失败，请重试！");
            }
          });
        })
        .catch((value) => {
          console.log(this.newTitle);
          let title = this.newTitle;

          httpService(
            "/javaApi/qtQuestionnaire/copyQuestionnaire",
            "id=" + id + "&flag=2&title=" + title,
            "post"
          ).then((data) => {
            if (data.code == 200) {
              ElMessage.success("复制成功");
              this.goDesign(data.obj);
              this.getQusetionnaireList();
            } else {
              ElMessage.error("删除失败，请重试！");
            }
            this.newTitle = "";
          });
        });
    },
    deleteQusetionnaire(id) {
      ElMessageBox.confirm("确定要删除本条记录吗？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          httpService(
            "/javaApi/qtQuestionnaire/deleteByIdLogical",
            "id=" + id,
            "post"
          ).then((data) => {
            if (data.code == 200) {
              ElMessage.success("删除成功,已存入回收站");
              this.getQusetionnaireList();
            } else {
              ElMessage.error("删除失败，请重试！");
            }
          });
        })
        .catch(() => { });
    },
    reloadData() {
      this.page = 1;
      this.getQusetionnaireList();
    },

    designTip(e) {
      console.log(e);
      this.nowUuid = e.uuid;
      this.nowId = e.id;
      if (e.status == 0) {
        this.goDesign(e.uuid);
      } else {
        this.dialogTableVisible = true;
      }
    },
    goDesign(uuid) {
      let routeData = this.$router.resolve({
        name: "Design",
        query: {
          p: uuid,
        },
      });
      // console.log(routeData);
      window.open(routeData.href, "_blank");
    },
    goAnalysis(uuid) {
      let routeData = this.$router.resolve({
        name: "Analysis",
        query: {
          p: uuid,
        },
      });
      window.open(routeData.href, "_blank");
    },
    importExcel() {
      this.$refs.addFileView.dialogFormVisible = true;
      this.$refs.addFileView.title = "批量导入问卷表";
      this.$refs.addFileView.uploadApiUrl = "/javaApi/qtQuestionnaire/importExcel";
    },
    exportExcel() {
      httpService(
        "/javaApi/qtQuestionnaire/exportExcel",
        {
          title: this.form.title,
          content: this.form.content,
          createName: this.form.createName,
        },
        "get"
      ).then((data) => {
        if (data.code == 200) {
          window.open(data.msg, "_blank");
        }
      });
    },
    onSubmit() {
      this.getQusetionnaireList();
    },
    // 每页记录数改变，size：回调参数，表示当前选中的“每页条数”
    changePageSize(size) {
      this.pageSize = size;
      this.limit = size;
      this.getQusetionnaireList();
    },

    // 改变页码，page：回调参数，表示当前选中的“页码”
    changeCurrentPage(page) {
      this.page = page;
      this.getQusetionnaireList();
    },
    tableRowClassName({ row, rowIndex }) {
      return "";
    },
    getQusetionnaireList() {
      httpService(
        "/javaApi/qtQuestionnaire/list/" + this.page + "/" + this.pageSize,
        {
          title: this.form.title,
          content: this.form.content,
          createName: this.form.createName,
          effect: 0,
          isTemplate: 0,
          status: this.form.status,
        },
        "get"
      ).then((data) => {
        this.list = data.list;
        this.total = data.total;
        this.pageCount = data.pages;
      });
    },
    formatDate(row, column) {
      let data = row[column.property];
      let dt = new Date(data);
      let month = dt.getMonth() + 1;
      if (month < 10) {
        month = "0" + month;
      }
      let hours = dt.getHours();
      if (hours < 10) {
        hours = "0" + hours;
      }
      let mDate = dt.getDate();
      if (mDate < 10) {
        mDate = "0" + mDate;
      }
      let minutes = dt.getMinutes();
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      let seconds = dt.getSeconds();
      if (seconds < 10) {
        seconds = "0" + seconds;
      }
      return (
        dt.getFullYear() +
        "-" +
        month +
        "-" +
        mDate +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds
      );
    },
  },
};
</script>
<style scoped>
.box {
  display: flex;
  width: 100%;
}

.box div {
  flex: 1;
  margin: 10px;
  text-align: center;
  cursor: pointer;
}

.box div:hover {
  flex: 1;
  border: 2px solid #409EFF;
  margin: 10px;
  text-align: center;
}

.checkedMode {
  border: 2px solid #409EFF;
}

.unCheckedMode {
  border: 2px solid #dedede;
}

.box div .p1 {
  color: #444;
  font-size: 18px;
}

.box div .p2 {
  color: #888;
}

.box-btn {
  margin: 0 auto;
  text-align: center;
  margin-top: 20px;
}

.el-main {
  padding: 0px;
}

.teacher-content {
  width: 100%;
}

.app-table {
  background: #eff3f5;
  padding: 10px;
}

.app-search {
  margin-top: 10px;
}

.app-separator {
  padding-top: 10px;
  padding-bottom: 20px;
  padding-left: 10px;
}

.app-body {
  background: white;
  padding: 20px 20px 10px 20px;
  margin-bottom: 10px;
  min-height: calc(100vh - 242px);
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-lighter);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-lighter);
}

.el-pagination {
  text-align: center;
  margin-top: 10px;
}
</style>

<style>
.el-dialog {
  position: relative;
  margin: 80px auto 50px;
}

.el-switch.is-disabled {
  opacity: 1;
}

.el-switch.is-disabled .el-switch__core,
.el-switch.is-disabled .el-switch__label {
  cursor: pointer;
}
</style>